<?php 

/**
 * Menu callback functinon
 */
function webformview_services(){
  $services = array(
      //'1' => 'get_services_1',
	  '1' => 'get_services_LEs',	// #autocomplete_path callback
      //'2' => 'get_services_2',
	  '2' => 'get_services_Locations',
      '3' => 'get_services_Locations_City',
  );
  
  $type = (isset($_REQUEST['type']))? $_REQUEST['type'] : '1';
  $type = (array_key_exists($type, $services)) ? $type : '1';
  $call_back = $services[$type];

  $arg = $_REQUEST;
  call_user_func_array($call_back, array('arg'=>$arg));
}

/**
 * #autocomplete_path callback: lookup 'webform_company' and return the '%Like%' company 
 */
function get_services_LEs($params){
  global $user;
  
  // #autocomplete_path: 'webformview/services/$input'
  $arg = arg();
  $input = trim($arg[2]); 
 
  $output = array();
 
  $sql = "SELECT company_code,long_name,short_name,city FROM {webform_company} WHERE long_name LIKE :input ORDER BY long_name ASC";
  $result = db_query($sql, array(':input'=>'%'.db_like($input).'%'));
  foreach ($result as $row) {
    $output[$row->company_code.' | '.check_plain($row->short_name).' | '. $row->city] = $row->company_code.' | '.check_plain($row->short_name).' | '. $row->city;
  }
  
  //return data in json format
  $return = drupal_json_output($output);
  echo $return;exit;
}

/**
 * Ajax callback for locations
 */
function get_services_Locations($params) {
  $locations = array();
  $options   = array();
  
  $html = '<option selected="selected" value="">- '.t('Select').' -</option>';
  $options[0] = array('', '- '.t('Select').' -');
  if (isset($params['code']) && !empty($params['code'])) {
    $locations = location_get_list($params['code']);
	foreach ($locations as $value) {
	  $html .= '<option value="'.$value->site_code.'">'.$value->site_name.' '.$value->site_code.'</option>';
	  $options[] = array($value->site_code, $value->site_name.' '.$value->site_code);
	}
  }
  
  $return = array(
    'htmldata' => $html,
	'options' => $options,
  );
  
  drupal_json_output($return);
  exit;
}

function get_services_Locations_City($params) {
  $city = '';
  
  if (isset($params['site_code']) && !empty($params['site_code'])) {
    $site_code = $params['site_code'];
	$locations = location_get_list(WEBFORM_DEFAULT_COUNTRY, $site_code);
	$city = $locations[$site_code]->city_name;
  }
  
  $return = array(
    'city' => $city,
  );
  
  drupal_json_output($return);
  exit; 
}

function get_services_1($params){
  global $user;
  
  $arg = arg();
  $input = $arg[2]; 
 
  $output = '';
  $length = mb_strlen($input);
  for($n=0;$n<$length;$n++){
  $myinput = truncate_utf8($input,$n+1);
    $output[] .= '"'.$myinput.'":"'.$myinput.'"';
  }
  $output = implode(',',$output);
  echo '{'.$output.'}';
  exit;
}

function get_services_2($params){
  global $user;

  echo '{"AF":"Afghanistan","AX":"Aland Islands","AL":"Albania","CN":"China"}';
  exit;
}

//--------------------------------------------------------------------------------------------------

/**
 * Wizard start form. Choose an animal.
 */
function webformview_company_start_form($form, &$form_state) {
//    print_r($form_state['value']);exit;
  $form_state['title'] = t('Company Search');
  
  $form['company_code'] = array(
    '#type' => 'textfield',
    '#title' => t('Company Code'),
    '#default_value' => '',
	'#size' => '30',
    //'#required' => TRUE,
  );
  $form['long_name'] = array(
    '#type' => 'textfield',
    '#title' => t('Company Name').":",
    '#default_value' => '',
	'#size' => '30',
    //'#required' => TRUE,
  );
  $form['city'] = array(
    '#type' => 'textfield',
    '#title' => t('Company City').":",
    '#default_value' => '',
	'#size' => '30',
    //'#required' => TRUE,
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#title' => t('Search'),
    '#default_value' => t('Search'),
  );

  return $form;
}

function webformview_company_start_form_submit(&$form, &$form_state) {
  if ($form_state['values']['op'] == t('Search')) {
    $object = new stdclass;
    $object->country = isset($form_state['country']) ? $form_state['country'] : WEBFORM_DEFAULT_COUNTRY;
    $object->company_code = isset($form_state['values']['company_code']) ? $form_state['values']['company_code'] : '';	
    $object->long_name = isset($form_state['values']['long_name']) ? $form_state['values']['long_name'] : '';
    $object->city = isset($form_state['values']['city']) ? $form_state['values']['city'] : '';
	
    if (!isset($_SESSION['ctools_search'])) {
        $_SESSION['ctools_search'] = NULL; 
    }
    $_SESSION['ctools_search'] = $object;
  }
  
  // Override where to go next based on the animal selected.
  //$form_state['clicked_button']['#next'] = 'results';
}

/*function webformview_company_results_form($form, &$form_state) {
  $form_state['title'] = t('search results');

  $form['company_code'] = array(
    '#type' => 'textfield',
    '#title' => t('Company Code').":",
    '#default_value' => $form_state['object']->company_code,
	'#size' => '8',
    //'#required' => TRUE,
  );
  $form['long_name'] = array(
    '#type' => 'textfield',
    '#title' => t('Company Name').":",
    '#default_value' => $form_state['object']->long_name,
	'#size' => '15',
    //'#required' => TRUE,
  );
  $form['city'] = array(
    '#type' => 'textfield',
    '#title' => t('City').":",
    '#default_value' => $form_state['object']->city,
	'#size' => '8',
    //'#required' => TRUE,
  );

  return $form;
}*/

function _search_company_data($object,$field) { 
  $output = '';
  $output .= '<br><br>'.'<div id="ctools-sample">'.'<h1>'.t('Results:').'</h1>'.'</div>';
  
  $like = '( 1=1 ';
  $param = array(':country'=>$object->country);
  if (isset($object->company_code) && $object->company_code) {
    $like .= "AND company_code LIKE :code "; 
    $param += array(':code'=>'%'.db_like($object->company_code).'%');
  }
  
  if (isset($object->long_name) && $object->long_name) {
    $like .= "AND long_name LIKE :name ";
    $param += array(':name'=>'%'.db_like($object->long_name).'%');
  }
  
  if (isset($object->city) && $object->city) {
    $like .= "AND city LIKE :city ";
    $param += array(':city'=>'%'.db_like($object->city).'%');
  }
  
  $like .= ')';
  
  // Create a table that we can have data removed from via AJAX.
  $header = array(t('Row'), t('Code'), t('Name'), t('Short Name'), t('City'), t('Actions'));
  $rows = array();
  
  $sql = "SELECT * FROM {webform_company} WHERE country=:country AND $like ORDER BY long_name ASC"; //echo $sql;exit;
  $result = db_query($sql, $param);
  
  $i = 1;
  foreach ($result as $row) {
    $rows[] = array(
      'class' => array('ajax-sample-row-'. $i),
      'data' => array(
                $i,
                $row->company_code,
		ctools_modal_text_button($row->long_name, 'webformview/ajax/company/select/'.$row->company_code.'/'.$object->country.'/'.$field, t('select')),
		$row->short_name,
		$row->city,
		ctools_modal_text_button(t('select'), 'webformview/ajax/company/select/'.$row->company_code.'/'.$object->country.'/'.$field, t('select')),
      ),
    );
    $i++;
  }
  $rows[] = array(
      'class' => array('ajax-sample-row-'. $i),
      'data' => array(
                $i,
                '0000',
		ctools_modal_text_button('None of Above', 'webformview/ajax/company/select/0000/All'.'/'.$field, t('select')),
		'',
		'None',
		ctools_modal_text_button(t('select'), 'webformview/ajax/company/select/0000/All'.'/'.$field, t('select')),
      ),
    );
  if ($i > 1) {
    $output .= theme('table', array('header' => $header, 'rows' => $rows, array('class' => array('ajax-sample-table'))));
  }
  else {
    $output .= "<br><font color='red'>".t('No result.')."</font>";    
  }
  
  return $output;
}

// Menu callback
function webformview_services_company($js=NULL, $country=NULL, $field=NULL) {
//  $country = WEBFORM_DEFAULT_COUNTRY;  
//  if (isset($nid)) {
//    $country_arr = webform_get_country($nid);
//    if (isset($country_arr['key']))
//      $country = $country_arr['key'];
//  }
  
  $country = isset($country) ? $country : WEBFORM_DEFAULT_COUNTRY;

  
  // Fall back if $js is not set.
  if (!$js) {
    return drupal_get_form('webformview_company_start_form');
  }

  ctools_include('modal');
  ctools_include('ajax');
  $form_state = array(
    'title' => t('Search'),
    'ajax' => TRUE,
    'country' => $country,  
  );
  $search_form = ctools_modal_form_wrapper('webformview_company_start_form', $form_state);

  // If Submit(用from_state检测表单提交状态)
  $output = array();
  if (!empty($form_state['executed'])) {
	$result_html = '';
	// Get search result by session filter
    if (isset($_SESSION['ctools_search'])) {
	  $data_table  = _search_company_data($_SESSION['ctools_search'],$field);
	  $result_html = drupal_render($search_form).''.$data_table;
    }
	$output[] = ctools_modal_command_display(t('Search Results'), $result_html);
	print ajax_render($output);exit;
  }
  else {
	print ajax_render($search_form);exit;
  }
}

/*function webformview_services_company_old($js = NULL, $step = NULL) {
  if ($js) {
    ctools_include('modal');
    ctools_include('ajax');
  }

  $form_info = array(
    'id' => 'search_company',
    'path' => "webformview/" . ($js ? 'ajax' : 'nojs') . "/company/%step",
    'show trail' => TRUE,
    'show back' => TRUE,
    'show cancel' => TRUE,
    'show return' => FALSE,
    'next callback' =>  'ctools_ajax_sample_wizard_next',
    'finish callback' => 'ctools_ajax_sample_wizard_finish',
    'cancel callback' => 'ctools_ajax_sample_wizard_cancel',
    // this controls order, as well as form labels
    'order' => array(
      'start' => t('Search'),
    ),
    // here we map a step to a form id.
    'forms' => array(
      // e.g. this for the step at wombat/create
      'start' => array(
        'form id' => 'webformview_company_start_form'
      ),
	  'results' => array(
        'form id' => 'webformview_company_results_form'
      ),
    ),
  );

  $object_id = 2;
  if (empty($step)) {
    ctools_ajax_sample_cache_clear($object_id);
    $step = 'start';
  }

  // This automatically gets defaults if there wasn't anything saved.
  $object = ctools_ajax_sample_cache_get($object_id);
  if (!isset($object->company_code) && !isset($object->long_name) && !isset($object->city)) {
    $form_info['order']['unknown'] = t('Keyword');
    $form_info['forms']['unknown'] = array('form id' => 'nothing');
  }
  else {
    $form_info['order']['results'] = t('Results');
  }

  $form_state = array(
    'ajax' => $js,
    // Put our object and ID into the form state cache so we can easily find it.
    'object_id' => $object_id,
    'object' => &$object,
  );

  // Send this all off to our form. This is like drupal_get_form only wizardy.
  ctools_include('wizard');
  $form = ctools_wizard_multistep_form($form_info, $step, $form_state);	//print_r($form);exit;
  $output = drupal_render($form);
  
  $data_table = _search_company_data($object);
  $output .= $data_table;

  if ($output === FALSE || !empty($form_state['complete'])) {
	$submit_return = 'test data..';
  }
  
  if ($js) {
    // If javascript is active, we have to use a render array.
    $commands = array();
    if ($output === FALSE || !empty($form_state['complete'])) {
      // Dismiss the modal.
      //$commands[] = ajax_command_html('#ctools-sample', $submit_return);
      $commands[] = ctools_modal_command_dismiss();
    }
    else if (!empty($form_state['cancel'])) {
      // If cancelling, return to the activity.
      $commands[] = ctools_modal_command_dismiss();
    }
    else {
      $commands = ctools_modal_form_render($form_state, $output);
    }
    print ajax_render($commands);
    exit;
  }
  else {
    if ($output === FALSE || !empty($form_state['complete'])) {
      return $animal;
    }
    else if (!empty($form_state['cancel'])) {
      drupal_goto('initiation/');
    }
    else {
      return $output;exit;
    }
  }
}*/

// Menu callback
function webformview_services_company_select($js=NULL, $company_code='', $country='', $field='') {
  ctools_include('modal');
  ctools_include('ajax');
  
  $company = array('company_code'=>'', 'long_name'=>'', 'city'=>'');
  if (!empty($company_code)) {
    $company = company_get_list($country, $company_code);
  }
  if($field==1){
    if($company['company_code']=='0000'){
        $commands[] = ajax_command_invoke('#webform-component-relocation-data--company-code', 'show');
        $commands[] = ajax_command_invoke('#webform-component-relocation-data--company-code label .form-required', 'show');
        $commands[] = ajax_command_invoke('#edit-submitted-relocation-data-company-code', 'addClass',array('required'));
        $commands[] = ajax_command_invoke('#webform-component-relocation-data--company-name', 'show');
        $commands[] = ajax_command_invoke('#webform-component-relocation-data--company-name label .form-required', 'show');
    }else{
        $commands[] = ajax_command_invoke('#webform-component-relocation-data--company-code', 'hide');
        $commands[] = ajax_command_invoke('#webform-component-relocation-data--company-code label .form-required', 'hide');
        $commands[] = ajax_command_invoke('#edit-submitted-relocation-data-company-code', 'removeClass',array('required'));
        $commands[] = ajax_command_invoke('#webform-component-relocation-data--company-name', 'hide');
        $commands[] = ajax_command_invoke('#webform-component-relocation-data--company-name label .form-required', 'hide');
    }
    $commands[] = ctools_ajax_command_attr('#edit-submitted-relocation-data-receiving-company-legal-entity2-code','value',$company['company_code']);
    $commands[] = ctools_ajax_command_attr('#edit-submitted-relocation-data-receiving-company-legal-entity2-code','readonly', 'readOnly');
    $commands[] = ajax_command_css('#edit-submitted-relocation-data-receiving-company-legal-entity2-code', array("color"=>"#999"));	
    $commands[] = ctools_ajax_command_attr('#edit-submitted-relocation-data-receiving-company-legal-entity2-name', 'value', $company['long_name']);
    $commands[] = ctools_ajax_command_attr('#edit-submitted-relocation-data-receiving-company-legal-entity2-name', 'readonly', 'readOnly');
    $commands[] = ajax_command_css('#edit-submitted-relocation-data-receiving-company-legal-entity2-name', array("color"=>"#999"));
    $commands[] = ctools_ajax_command_attr('#edit-submitted-relocation-data-receiving-company-legal-entity2-city', 'value', $company['city']);
    $commands[] = ctools_ajax_command_attr('#edit-submitted-relocation-data-receiving-company-legal-entity2-city', 'readonly', 'readOnly');
    $commands[] = ajax_command_css('#edit-submitted-relocation-data-receiving-company-legal-entity2-city', array("color"=>"#999"));
  }
   if($field==2){
    $commands[] = ctools_ajax_command_attr('#edit-submitted-personal-data-legal-entity-which-employee-signed-their-contract-for-code','value',$company['company_code']);
    $commands[] = ctools_ajax_command_attr('#edit-submitted-personal-data-legal-entity-which-employee-signed-their-contract-for-code','readonly', 'readOnly');
    $commands[] = ajax_command_css('#edit-submitted-personal-data-legal-entity-which-employee-signed-their-contract-for-code', array("color"=>"#999"));	
    $commands[] = ctools_ajax_command_attr('#edit-submitted-personal-data-legal-entity-which-employee-signed-their-contract-for-name', 'value', $company['long_name']);
    $commands[] = ctools_ajax_command_attr('#edit-submitted-personal-data-legal-entity-which-employee-signed-their-contract-for-name', 'readonly', 'readOnly');
    $commands[] = ajax_command_css('#edit-submitted-personal-data-legal-entity-which-employee-signed-their-contract-for-name', array("color"=>"#999"));
    $commands[] = ctools_ajax_command_attr('#edit-submitted-personal-data-legal-entity-which-employee-signed-their-contract-for-city', 'value', $company['city']);
    $commands[] = ctools_ajax_command_attr('#edit-submitted-personal-data-legal-entity-which-employee-signed-their-contract-for-city', 'readonly', 'readOnly');
    $commands[] = ajax_command_css('#edit-submitted-personal-data-legal-entity-which-employee-signed-their-contract-for-city', array("color"=>"#999"));
  }
  $commands[] = ctools_modal_command_dismiss();
  
  $output = $commands;
   
  //Render the output
  print ajax_render($commands);
  exit();        
}